package club.banyuan;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;

public class UdpServer extends Thread{
    private DatagramSocket datagramSocket;

    public UdpServer(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        try {
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
            while (true) {
                datagramSocket.receive(datagramPacket);
                byte[] data = datagramPacket.getData();
                int length = datagramPacket.getLength();
                System.out.println(new String(data, 0, length));
            }
        } catch (IOException e) {
            System.out.println("异常");
        }
    }

    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(5000);
        UdpServer thread = new UdpServer(datagramSocket);
        thread.start();

        Scanner scanner = new Scanner(System.in);
        if ("quit".equalsIgnoreCase(scanner.next())){
            System.out.println("服务器退出");
            datagramSocket.close();
        }
    }
}
